import base64
import json
import pickle

from django import http
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from utils import constants
from utils.response_code import RETCODE


class CartsView(View):
    """购物车"""

    def get(self, request):
        """展示购物车页面信息"""
        user = request.user
        if user.is_authenticated:
            """用户已登录"""
            """查询redis中的购物车"""
            redis_conn = get_redis_connection('carts')
            # 获取当前id下的购物车数据
            redis_carts = redis_conn.hgetall('carts_%s' % user.id)
            # 获取当前id下的选中数据
            carts_selected = redis_conn.smembers('selected_%s' % user.id)
            carts_dict = {}
            for sku_id, count in redis_carts.items():
                carts_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in carts_selected
                }
        else:
            """未登录时从cookie中获取"""
            carts_str = request.COOKIES.get('carts')
            if carts_str:
                carts_dict = pickle.loads(base64.b64decode(carts_str.encode()))
            else:
                carts_dict = {}
        skus_id = carts_dict.keys()
        sku_ids = []
        for id_sku in skus_id:
            if isinstance(id_sku, int):
                sku_ids.append(id_sku)
        skus = SKU.objects.filter(id__in=sku_ids)
        carts_skus = []
        for sku in skus:
            carts_skus.append(
                {
                    'id': sku.id,
                    'name': sku.name,
                    'count': carts_dict.get(sku.id).get('count'),
                    'selected': str(carts_dict.get(sku.id).get('selected')),
                    'default_image_url': sku.default_image,
                    'price': str(sku.price),
                    'amount': str(sku.price * carts_dict.get(sku.id).get('count'))
                }
            )

        context = {
            'cart_skus': carts_skus,
        }

        return render(request, 'cart.html', context)

    def post(self, request):
        """添加商品到购物车"""

        # 获取参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)
        # 校验参数
        if not all([sku_id, count]):
            return http.HttpResponseBadRequest('缺少参数')

        try:
            sku_sku = SKU.objects.get(id=sku_id)
            stk = sku_sku.stock
            if stk == 0:
                return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '库存不足'})
        except:
            return http.HttpResponseBadRequest('没有该商品')

        user = request.user
        if user.is_authenticated:
            """用户登录后进行添加"""
            # 连接redis
            redis_conn = get_redis_connection('carts')
            # 建立管道
            pl = redis_conn.pipeline()
            pl.hincrby('carts_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            pl.execute()

            return http.JsonResponse({"code": RETCODE.OK, 'errmsg': 'ok'})

        else:
            """用户未登录时进行添加"""
            # 从cookie中获取购物车的变量
            str_carts = request.COOKIES.get('carts')
            # 如果存在，说明之前操作过购物车
            if str_carts:
                carts_dict = pickle.loads(base64.b64decode(str_carts.encode()))
            else:
                carts_dict = {}

            # 判断该商品是否存在购物车中
            if sku_id in carts_dict:
                # 如果存在，商品数量累加
                source_count = carts_dict[sku_id]['count']
                count += source_count
            carts_dict[sku_id] = {
                'count': count,
                'selected': selected,
            }
            # 将数据进行加密
            carts_cookie = base64.b64encode(pickle.dumps(carts_dict)).decode()
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
            # 将购物车的信息存入到cookie中
            response.set_cookie('carts', carts_cookie, max_age=constants.CARTS_COOKIE_EXPIRES)
            return response

    def put(self, request):
        """修改购物车数据"""

        # 获取参数
        json_dict = json.loads(request.body.decode())
        count = json_dict.get('count')
        sku_id = json_dict.get('sku_id')
        selected = json_dict.get('selected')

        # 参数
        if not all([count, sku_id]):
            return http.HttpResponseBadRequest('参数不足')
        try:
            count = int(count)
        except:
            return http.HttpResponseBadRequest('count参数错误')

        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseBadRequest('selected参数错误')
        try:
            sku = SKU.objects.get(id=sku_id)
        except:
            return http.HttpResponseBadRequest('does not found the sku_id')

        # 判断是否登录
        user = request.user

        if user and user.is_authenticated:
            """登录调用redis数据库"""
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            pl.hset('carts_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                pl.srem('selected_%s' % user.id, sku_id)

            pl.execute()

            cart_sku = {
                'id': sku_id,
                'count': count,
                'name': sku.name,
                'price': sku.price,
                'amount': int(sku.price) * int(count),
                'default_image_url': sku.default_image,
                'selected': selected,
            }

            return http.JsonResponse({"code": RETCODE.OK, 'errmsg': 'ok', 'cart_sku': cart_sku})

        else:
            """未登录调用cookie"""
            str_carts = request.COOKIES.get('carts')

            if str_carts:
                carts = pickle.loads(base64.b64decode(str_carts.encode()))
            else:
                carts = {}

            carts[sku_id] = {
                'count': count,
                'selected': selected,
            }

            cart_sku = {
                'id': sku_id,
                'count': count,
                'name': sku.name,
                'price': sku.price,
                'amount': int(sku.price) * int(count),
                'default_image_url': sku.default_image,
                'selected': selected,
            }
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'cart_sku': cart_sku})

    def delete(self, request):
        """删除商品"""
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get("sku_id")

        try:
            sku = SKU.objects.get(id=sku_id)
        except:
            return http.HttpResponseBadRequest('未找到该商品')

        user = request.user

        if user and user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            pl.hdel('carts_%s' % user.id, sku_id)
            pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除成功'})

        else:
            str_carts = request.COOKIES.get("carts")
            if str_carts:
                carts = pickle.loads(base64.b64decode(str_carts.encode()))
            else:
                carts = {}
            if sku_id in carts:
                del carts[sku_id]
            cookie_carts = base64.b64encode(pickle.dumps(carts)).decode()
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除成功'})
            response.set_cookie('carts', cookie_carts, max_age=constants.CARTS_COOKIE_EXPIRES)
            return response


class SelectionView(View):
    """全选"""

    def put(self, request):
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected')
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseBadRequest("the selected is does not found")

        user = request.user

        if user and user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            carts = redis_conn.hgetall('carts_%s' % user.id)
            skus = carts.keys()
            if selected:
                redis_conn.sadd('selected_%s' % user.id, *skus)
            else:
                redis_conn.srem('selected_%s' % user.id, *skus)

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})

        else:
            str_carts = request.COOKIES.get("carts")

            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
            if str_carts:
                carts = pickle.loads(base64.b64decode(str_carts.encode()))

                for sku_id in carts:
                    carts[sku_id]['selected'] = selected

                cookie_carts = base64.b64encode(pickle.dumps(carts)).decode()
                response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
                response.set_cookie('carts', cookie_carts, max_age=constants.CARTS_COOKIE_EXPIRES)
                return response


class CartsSimpleView(View):
    """购物车小界面展示"""

    def get(self, request):

        # 确认用户是否登录
        user = request.user

        if user and user.is_authenticated:
            """redis中查询"""

            redis_conn = get_redis_connection('carts')

            carts = redis_conn.hgetall('carts_%s' % user.id)
            selected = redis_conn.smembers('selected_%s' % user.id)
            carts_dict = {}
            for sku_id, count in carts.items():
                carts_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in selected,
                }

        else:
            str_carts = request.COOKIES.get('carts')
            if str_carts:
                carts_dict = pickle.loads(base64.b64decode(str_carts.encode()))
            else:
                carts_dict = {}

        sku_ids = carts_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append(
                {
                    'id': sku.id,
                    'name': sku.name,
                    'count': carts_dict.get(sku.id).get('count'),
                    'default_image_url': sku.default_image,
                }
            )

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'cart_skus': cart_skus})
